﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using Framework;

namespace Enterprise
{
    public class TeamStyleService : BaseService
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="name"></param>
        /// <param name="nameEn"></param>
        /// <param name="description"></param>
        /// <param name="descriptionEn"></param>
        /// <param name="sort"></param>
        /// <param name="filedata"></param>
        /// <returns></returns>
        public string[] Add(string name, string nameEn, string description, string descriptionEn, int sort, HttpPostedFileBase filedata)
        {
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = "~/Upload/TeamStyle/",
                    IsAdaptive = true,
                    IsImage = true,
                    IsGenerateThumbnail = true,
                    FileMaxLength = 1024 * 1024 * 2,
                    ThumbnailHeight = 185,
                    ThumbnailWidth = 165,
                    ThumbnailPrefix = "thum"
                };
                uploadHelper.Save();
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var sbSql = new StringBuilder();
            sbSql.Append("insert into tbTeamStyle(");
            sbSql.Append("CoNormalImage,CoSmallImage,CoBigImage,CoName,CoNameEn,CoDescription,CoDescription,CoSort");
            sbSql.Append(") values(");
            sbSql.Append("@CoNormalImage,@CoSmallImage,@CoBigImage,@CoName,@CoNameEn,@CoDescription,@CoDescription,@CoSort");
            sbSql.Append(")");
            var parameters = new[]
                                {
                                    new SqlParameter("@CoNormalImage", SqlDbType.VarChar,255),
                                    new SqlParameter("@CoSmallImage", SqlDbType.VarChar,255),
                                    new SqlParameter("@CoBigImage", SqlDbType.VarChar,255),
                                    new SqlParameter("@CoName", SqlDbType.VarChar,255),
                                    new SqlParameter("@CoNameEn", SqlDbType.VarChar,255),
                                    new SqlParameter("@CoDescription", SqlDbType.Text),  
                                    new SqlParameter("@CoDescriptionEn", SqlDbType.Text),  
                                    new SqlParameter("@CoSort", SqlDbType.Int)
                                };

            parameters[0].Value = fileName;
            parameters[1].Value = thumFileName;
            parameters[2].Value = fileName;
            parameters[3].Value = name;
            parameters[4].Value = nameEn;
            parameters[5].Value = description;
            parameters[6].Value = descriptionEn;
            parameters[7].Value = sort;
            var rows = DbHelperSql.Add(sbSql.ToString(), parameters).SafeToInt();
            if (rows > 0)
            {
                return new[] { rows.ToString(CultureInfo.InvariantCulture), fileName, thumFileName };
            }
            throw new Exception("添加失败！");
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="nameEn"></param>
        /// <param name="description"></param>
        /// <param name="descriptionEn"></param>
        /// <param name="sort"></param>
        /// <param name="filedata"></param>
        /// <returns></returns>
        public int Eidt(int id, string name, string nameEn, string description, string descriptionEn, int sort, HttpPostedFileBase filedata)
        {
            Check.Argument.IsNotOutOfLength(name, 50, "图片名称");
            Check.Argument.IsNotOutOfLength(nameEn, 50, "图片名称(En)");
            var sb = new StringBuilder();
            sb.Append("update tbTeamStyle set ");
            sb.Append("CoName=@CoName,CoDescription=@CoDescription,CoNameEn=@CoNameEn,CoDescriptionEn=@CoDescriptionEn");
            SqlParameter[] parameters;
            if (filedata != null && filedata.ContentLength > 0)
            {
                sb.Append(",CoNormalImage=@CoNormalImage,CoSmallImage=@CoSmallImage,CoBigImage=@CoBigImage");
                parameters = new[]
                    {
                        new SqlParameter("@CoName", SqlDbType.VarChar, 255),
                        new SqlParameter("@CoDescription", SqlDbType.Text),
                        new SqlParameter("@CoNameEn", SqlDbType.VarChar, 255),
                        new SqlParameter("@CoDescriptionEn", SqlDbType.Text),
                        new SqlParameter("@CoSort", SqlDbType.Int),
                        new SqlParameter("@CoNormalImage", SqlDbType.VarChar, 255),
                        new SqlParameter("@CoSmallImage", SqlDbType.VarChar, 255),
                        new SqlParameter("@CoBigImage", SqlDbType.VarChar, 255),
                        new SqlParameter("@id", SqlDbType.Int)
                    };
                parameters[0].Value = name;
                parameters[1].Value = description;
                parameters[2].Value = nameEn;
                parameters[3].Value = descriptionEn;
                parameters[4].Value = sort;
                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = "~/Upload/TeamStyle/",
                    IsAdaptive = true,
                    IsImage = true,
                    IsGenerateThumbnail = true,
                    FileMaxLength = 1024 * 1024 * 2,
                    ThumbnailHeight = 185,
                    ThumbnailWidth = 165,
                    ThumbnailPrefix = "thum"
                };
                uploadHelper.Save();
                var fileName = uploadHelper.FileName;
                var thumFileName = uploadHelper.ThumbnailFileName;
                parameters[5].Value = fileName;
                parameters[6].Value = thumFileName;
                parameters[7].Value = fileName;
                parameters[8].Value = id;
                var path = HttpContext.Current.Server.MapPath("~/Upload/TeamStyle/");
                var ds = DbHelperSql.Query("select * from tbTeamStyle where coTeamStyleid=@id".FormatWith(id));
                foreach (DataRow item in ds.Tables["ds"].Rows)
                {
                    FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                    FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                    FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
                }
            }
            else
            {
                parameters = new[]
                                {
                                    new SqlParameter("@CoName", SqlDbType.VarChar, 255),
                                    new SqlParameter("@CoDescription", SqlDbType.Text),
                                    new SqlParameter("@CoNameEn", SqlDbType.VarChar, 255),
                                    new SqlParameter("@CoDescriptionEn", SqlDbType.Text),
                                    new SqlParameter("@CoSort", SqlDbType.Int),
                                    new SqlParameter("@id", SqlDbType.Int)
                                };
                parameters[0].Value = name;
                parameters[1].Value = description;
                parameters[2].Value = nameEn;
                parameters[3].Value = descriptionEn;
                parameters[4].Value = sort;
                parameters[5].Value = id;
            }
            sb.Append(" where CoTeamStyleId=@id");
            var rows = DbHelperSql.ExecuteSql(sb.ToString(), parameters).SafeToInt();
            if (rows > 0)
            {
                return rows;
            }
            throw new Exception("修改失败！");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            var path = HttpContext.Current.Server.MapPath("~/Upload/TeamStyle/");
            var ds = DbHelperSql.Query("select * from tbTeamStyle where coTeamStyleid={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            int rows = DbHelperSql.ExecuteSql("delete  from tbTeamStyle where coTeamStyleid={0}".FormatWith(id));
            if (!(rows > 0))
                throw new Exception("记录不存在！");
        }
        /// <summary>
        ///  获取表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageValue"></param>
        /// <param name="rowsValue"></param>
        /// <returns></returns>
        public Table GetTable(string name, int pageValue, int rowsValue)
        {
            var sbSqlWhere = new StringBuilder();
            sbSqlWhere.Append(" where CoName like '%'+@CoName+'%' or  CoNameEn like '%'+@CoName+'%'");
            var parameters = new[]
                {
                    new SqlParameter("@CoName", SqlDbType.VarChar, 255)
                };
            parameters[0].Value = name.SqlLike();
            int total = DbHelperSql.GetSingle("select count(*) from TbTeamStyle {0}".FormatWith(sbSqlWhere), parameters).SafeToInt();
            var sbSql = new StringBuilder();
            sbSql.AppendFormat("select top {0} * from TbTeamStyle {1} ", rowsValue, sbSqlWhere);
            if (pageValue > 1)
                sbSql.AppendFormat(" and CoTeamStyleId not in (select top {0} CoTeamStyleId from TbTeamStyle {1} order by CoTeamStyleId) ", rowsValue * (pageValue - 1), sbSqlWhere);
            sbSql.Append(" order by CoTeamStyleId");
            var ds = DbHelperSql.Query(sbSql.ToString(), parameters);
            return new Table { Rows = ds.Tables["ds"].Rows, Total = total };
        }
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            var rows = DbHelperSql.Query("select *  from TbTeamStyle  where CoTeamStyleId={0}".FormatWith(id)).Tables["ds"].Rows;
            return rows[0];
        }
    }
}
